const bcrypt = require("bcryptjs");
const { getOneUserInfo } = require("../service/user.service");
const {
    userFormatError,
    userAlreadyExisted,
    userRegisterError,
    userDoesNotExisted,
    userLoginError,
    invalidPassword
} = require("../constant/err.type");
const userValidator = async (ctx, next) => {
    const { userName, password } = ctx.request.body;
    // 合法性检验
    if (!userName || !password) {
        console.error("用户名或密码为空", ctx.request.body);
        ctx.app.emit("error", userFormatError, ctx);
        return;
    }

    await next();
};
// 合理性检测
const userVerify = async (ctx, next) => {
    const { userName } = ctx.request.body;
    try {
        const res = await getOneUserInfo({ userName });

        if (res) {
            console.error("用户名已经存在", ctx.request.body);
            ctx.app.emit("error", userAlreadyExisted, ctx);
            return;
        }
    } catch (err) {
        console.error("获取用户名失败", err);
        ctx.app.emit("error", userRegisterError, ctx);
        return;
    }

    await next();
};
// 密码加密
const cryptPassword = async (ctx, next) => {
    const { password } = ctx.request.body;
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);
    ctx.request.body.password = hash;
    await next();
};
// 验证登录 用户名是否存在检测
const Verifylogin = async (ctx, next) => {
    const { userName, password } = ctx.request.body;

    try {
        console.log("验证登录", userName, password);
        const res = await getOneUserInfo({ userName });
        // 1.用户名验证
        if (!res) {
            console.error("用户名不存在", { userName });
            ctx.app.emit("error", userDoesNotExisted, ctx);
            return;
        }
        // 2.密码验证
        console.log("密码验证", res.password, password);
        if (!bcrypt.compareSync(password, res.password)) {
            console.error("密码不匹配！", password)
            ctx.app.emit('error', invalidPassword, ctx)
            return;
        }
    } catch (err) {
        console.error("用户登录失败", err);
        ctx.app.emit("error", userLoginError, ctx);
        return;
    }


    await next();
}

module.exports = { userValidator, userVerify, cryptPassword, Verifylogin };